package com.yangtu.nearbyshop.admin.job;

import com.alibaba.druid.support.json.JSONUtils;
import com.yangtu.nearbyshop.db.domain.NearbyshopBdSettle;
import com.yangtu.nearbyshop.db.domain.NearbyshopMercRebate;
import com.yangtu.nearbyshop.db.domain.NearbyshopMercRebateSettle;
import com.yangtu.nearbyshop.db.domain.NearbyshopMercSettle;
import com.yangtu.nearbyshop.db.service.itf.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * BD日统计
 */
@Component
public class BdCountJob {
    private final Log logger = LogFactory.getLog(BdCountJob.class);

    @Autowired
    private INearbyshopBdService bdService;

    @Autowired
    private INearbyshopBdSettleService settleService;

    @Autowired
    private INearbyshopMercSettleService mercSettleService;

    @Autowired
    private INearbyshopMercRebateService rebateService;

    @Autowired
    private INearbyshopMercRebateSettleService rebateSettleService;

    @Autowired
    private INearbyshopOrderService orderService;

    /**
     * 统计BD周销售额
     * <p>
     * 每周一的凌晨1点10分执行，对上周-到周日的数据进行统计
     */
    //@Scheduled(cron = "0 10 1 ? * MON")
    //@Scheduled(fixedDelay = 5 * 60 * 1000)
    public void countBdSale() {
        logger.info("开始：系统开启任务=统计上周BD销量");
        String startTime = getPastDate(7);
        String endTime = getPastDate(1);
        List<NearbyshopBdSettle> list = bdService.getBdSettleByWeek(startTime + " 00:00:00",endTime + " 23:59:59");
        for(NearbyshopBdSettle settle:list){
            settle.setAddTime(new Date());
            settle.setTimeDur(startTime.replaceAll("-","/")+"-" + endTime.replaceAll("-","/"));
        }
        settleService.saveBatch(list);

        logger.info("结束：系统结束任务=统计上周BD销量。dataSize=" + list.size());
    }

    /**
     * 统计门店周销售额
     * <p>
     * 每周一的凌晨1点15分执行，对上周-到周日的数据进行统计
     */
    @Scheduled(cron = "0 15 1 ? * MON")
    //@Scheduled(fixedDelay = 5 * 60 * 1000)
    public void countMercSale() {
        logger.info("系统开启任务=统计上周门店销量");
        String startTime = getPastDate(7);
        String endTime = getPastDate(1);
        List<NearbyshopMercRebate> rebates = new ArrayList<>();
        List<NearbyshopMercSettle> list = mercSettleService.getMercSettleByWeek(startTime + " 00:00:00",endTime + " 23:59:59");
        for(NearbyshopMercSettle settle:list){
            settle.setAddTime(new Date());
            settle.setTimeDur(startTime.replaceAll("-","/")+"-" + endTime.replaceAll("-","/"));
            NearbyshopMercRebateSettle weekSettle =rebateSettleService.getWeekRebateSettle(null,settle.getMercNo(),startTime,endTime);
            NearbyshopMercRebate rebateAmount = benefitByAmount(settle,weekSettle);
            NearbyshopMercRebate rebateCount = benefitByCount(settle,startTime,endTime);
            if(null != rebateAmount){
                rebates.add(rebateAmount);
            }
            if(null != rebateCount){
                rebates.add(rebateCount);
            }
        }
        rebateService.saveBatch(rebates);
        mercSettleService.saveBatch(list);
        logger.info("结束：系统结束任务=统计上周门店销量。data=" + JSONUtils.toJSONString(list));
    }

    public NearbyshopMercRebate benefitByAmount(NearbyshopMercSettle mercSettle, NearbyshopMercRebateSettle weekSettle){
        //1.给团长进行商品返利
        logger.info("门店周营业额返利检测MercNo=" + mercSettle.getMercNo()+",amount="+mercSettle.getAmount());
        NearbyshopMercRebate settle = new NearbyshopMercRebate();
        BigDecimal fenzAmount = BigDecimal.ZERO;
        if(mercSettle.getAmount().doubleValue()>=1050 && mercSettle.getAmount().doubleValue()<2100){
            fenzAmount = new BigDecimal(10);
            settle.setRebateDesc("营业额银牌任务返利"+fenzAmount.toPlainString()+"元");
        }else if(mercSettle.getAmount().doubleValue()>=2100 && mercSettle.getAmount().doubleValue()<4200){
            fenzAmount = new BigDecimal(25);
            settle.setRebateDesc("营业额金牌任务返利"+fenzAmount.toPlainString()+"元");
        }else if(mercSettle.getAmount().doubleValue()>=4200 && mercSettle.getAmount().doubleValue()<10500){
            fenzAmount = weekSettle.getAmount().multiply(new BigDecimal("0.1")).setScale(2, BigDecimal.ROUND_DOWN).stripTrailingZeros();
            settle.setRebateDesc("营业额铂金任务返利"+fenzAmount.toPlainString()+"元");
        }else if(mercSettle.getAmount().doubleValue()>=10500){
            fenzAmount = weekSettle.getAmount().multiply(new BigDecimal("0.15")).setScale(2, BigDecimal.ROUND_DOWN).stripTrailingZeros();
            settle.setRebateDesc("营业额钻石任务返利"+fenzAmount.toPlainString()+"元");
        }else {
            logger.info("门店周营业额返利检测MercNo=" + mercSettle.getMercNo()+",不返利");
            return null;
        }
        logger.info("门店周营业额返利检测MercNo=" + mercSettle.getMercNo()+",返利金额=" + fenzAmount);
        settle.setAddTime(new Date());
        settle.setAmount(fenzAmount);
        settle.setMercNo(mercSettle.getMercNo());
        settle.setRebateOrderId(null);
        settle.setRebateType("fanli-saleAmount");
        settle.setItems("营业额返利:"+mercSettle.getAmount());
        return settle;
    }

    public NearbyshopMercRebate benefitByCount(NearbyshopMercSettle mercSettle, String startTime, String endTime){
        int count = Integer.valueOf(orderService.sumAllUser(mercSettle.getMercNo(),
                startTime+" 00:00:00",endTime+" 23:59:59"));
        logger.info("门店周下单人数返利检测MercNo=" + mercSettle.getMercNo()+"," +
                "count="+count);

        //1.给团长进行商品返利
        NearbyshopMercRebate settle = new NearbyshopMercRebate();
        BigDecimal fenzAmount = BigDecimal.ZERO;
        if(count>=35 && count<105){
            fenzAmount = new BigDecimal(5);
            settle.setRebateDesc("下单人数铜牌任务返利"+fenzAmount.toPlainString()+"元");
        }else if(count>=105 && count<140){
            fenzAmount = new BigDecimal(10);
            settle.setRebateDesc("下单人数银牌任务返利"+fenzAmount.toPlainString()+"元");
        }else if(count>=140 && count<175){
            fenzAmount = new BigDecimal(30);
            settle.setRebateDesc("下单人数金牌任务返利"+fenzAmount.toPlainString()+"元");
        }else if(count>=175 && count<350){
            fenzAmount = new BigDecimal(50);
            settle.setRebateDesc("下单人数铂金任务返利"+fenzAmount.toPlainString()+"元");
        }else if(count>=350){
            fenzAmount = mercSettle.getAmount().multiply(new BigDecimal("0.2")).setScale(2, BigDecimal.ROUND_DOWN).stripTrailingZeros();
            settle.setRebateDesc("下单人数钻石任务返利"+fenzAmount.toPlainString()+"元");
        }else {
            logger.info("门店周下单人数返利检测MercNo=" + mercSettle.getMercNo()+"," +
                    "不返利");
            return null;
        }
        logger.info("门店周下单人数返利检测MercNo=" + mercSettle.getMercNo()+"," +
                "返利金额=" + fenzAmount);
        settle.setAddTime(new Date());
        settle.setAmount(fenzAmount);
        settle.setMercNo(mercSettle.getMercNo());
        settle.setRebateOrderId(null);
        settle.setRebateType("fanli-saleCount");
        settle.setItems("下单人数返利:"+count);
        return settle;
    }

    /**
     * 获取过去第几天的日期
     *
     * @param past
     * @return
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

}
